package com.sixth.stock.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sixth.core.entity.*;
import com.sixth.core.feign.UserFeign;
import com.sixth.core.util.WebUtil;
import com.sixth.core.vo.R;
import com.sixth.stock.mapper.InventoryLogMapper;
import com.sixth.stock.mapper.MedicinesMapper;
import com.sixth.stock.mapper.PurchaseItemMapper;
import com.sixth.stock.service.PurchaseService;
import com.sixth.stock.mapper.PurchaseMapper;
import com.sixth.stock.vo.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author Administrator
 * @description 针对表【stock_purchase】的数据库操作Service实现
 * @createDate 2024-08-14 19:56:44
 */
@Service
public class PurchaseServiceImpl extends ServiceImpl<PurchaseMapper, Purchase> implements PurchaseService {
    @Resource
    private PurchaseMapper purchaseMapper;
    @Resource
    private PurchaseItemMapper purchaseItemMapper;
    @Resource
    private MedicinesMapper medicinesMapper;
    @Resource
    private InventoryLogMapper inventoryLogMapper;
    @Resource
    private UserFeign userFeign;
    private static String pur = "his_order_status";
    private String getStatus(String description)    {
        List<DictData> data = userFeign.listByType(pur).getData();
        for (DictData dictData : data) {
            if (dictData.getDictLabel().contains(description)){
                return dictData.getDictValue();
            }
        }
        return "1";
    }

    @Override
    public R<IPage<Purchase>> selectByPage(PurchaseVo purchaseVo) {

        Integer pageSize = purchaseVo.getPageSize();
        Integer pageNum = purchaseVo.getPageNum();
        if (pageSize == null || pageNum == null || pageNum <= 0 || pageSize <= 0) {
            pageNum = 1;
            pageSize = 5;
        }
        IPage<Purchase> page =new Page<>(pageNum,pageSize);
        QueryWrapper<Purchase> queryWrapper = new QueryWrapper<>();
        if (purchaseVo.getProviderId() != null&& !purchaseVo.getProviderId() .equals("") ) {
            queryWrapper.like("provider_id",purchaseVo.getProviderId());
        }
        if (purchaseVo.getApplyUserName() != null&& !purchaseVo.getProviderId() .equals("")) {
            queryWrapper.like("apply_user_name",purchaseVo.getApplyUserName());
        }
        if (purchaseVo.getStatus() != null&&!purchaseVo.getStatus() .equals("")) {
            queryWrapper.eq("status",purchaseVo.getStatus());
        }
        queryWrapper.orderByDesc("create_time");
        IPage<Purchase> purchaseIPage = purchaseMapper.selectPage(page, queryWrapper);
        return R.ok(purchaseIPage);
    }

    @Override
    public R<IPage<Purchase>> listByStatus(PurchaseVo purchaseVo) {
        Integer pageSize = purchaseVo.getPageSize();
        Integer pageNum = purchaseVo.getPageNum();
        if (pageSize == null || pageNum == null || pageNum <= 0 || pageSize <= 0) {
            pageNum = 1;
            pageSize = 5;
        }
        IPage<Purchase> page =new Page<>(pageNum,pageSize);
        QueryWrapper<Purchase> queryWrapper = new QueryWrapper<>();
        //根据状态查询，仅仅待审核
        queryWrapper.eq("status", getStatus("待审核"));
        if (purchaseVo.getApplyUserName()!= null&& !purchaseVo.getApplyUserName().equals("")){
            queryWrapper.like("apply_user_name",purchaseVo.getApplyUserName());
        }
        if (purchaseVo.getProviderId()!= null&& !purchaseVo.getProviderId().equals("")){
            queryWrapper.eq("provider_id",purchaseVo.getProviderId());
        }
        queryWrapper.orderByDesc("create_time");
        IPage<Purchase> purchaseIPage = purchaseMapper.selectPage(page, queryWrapper);
        return R.ok(purchaseIPage);
    }

    @Override
    public R submit(String purchaseId) {
        //更改采购单的状态为2，表示待审核
        Purchase purchase = purchaseMapper.selectById(purchaseId);
        if (purchase != null) {
            purchase.setStatus(getStatus("待审核"));
            purchaseMapper.updateById(purchase);
            return R.ok();
        }
        return R.error("采购单不存在");
    }

    @Override
    public R doInvalid(String purchaseId) {
        //更改采购单的状态为5，表示作废
        Purchase purchase = purchaseMapper.selectById(purchaseId);
        if (purchase != null) {
            purchase.setStatus(getStatus("作废"));
            purchaseMapper.updateById(purchase);
            return R.ok();
        }
        return R.error("采购单不存在");
    }

    @Override
    public R doInventory(String purchaseId) {
        Snowflake snowflake = IdUtil.getSnowflake();
        //更改采购单的状态为6，表示入库
        Purchase purchase = purchaseMapper.selectById(purchaseId);
        String providerId = purchase.getProviderId();
        User data = userFeign.getByPhone(WebUtil.getUsername()).getData();
        String userName = data.getUserName();
        if (purchase != null) {
            purchase.setStatus(getStatus("入库"));
            purchase.setStorageOptUser(userName);
            purchase.setStorageOptTime(new Date());
            purchaseMapper.updateById(purchase);
        }
        List<PurchaseItem> purchaseItems = purchaseItemMapper.selectList(new QueryWrapper<PurchaseItem>().eq("purchase_id", purchaseId));
        for (PurchaseItem purchaseItem : purchaseItems) {
            String medicinesId = purchaseItem.getMedicinesId();
            Integer purchaseNumber = purchaseItem.getPurchaseNumber();
            Medicines medicines = medicinesMapper.selectById(medicinesId);
            if (medicines != null) {
                medicines.setMedicinesStockNum(medicines.getMedicinesStockNum() + purchaseNumber);
                medicinesMapper.updateById(medicines);
            }String id = ""+snowflake.nextId();
            BigDecimal tradePrice = purchaseItem.getTradePrice();
            BigDecimal prescriptionPrice = medicines.getPrescriptionPrice();
            BigDecimal tradeTotalAmount = purchaseItem.getTradeTotalAmount();
            BigDecimal inventoryTotalAmount = tradePrice.multiply(prescriptionPrice);
            String batchNumber = purchaseItem.getBatchNumber()==null?purchaseItem.getBatchNumber():"";
            System.out.println("+++++++++++++++++++batch" +purchaseItem.getBatchNumber());
            String medicinesType = medicines.getMedicinesType();
            String prescriptionType = medicines.getPrescriptionType();
            String medicinesName = medicines.getMedicinesName();
            String producterId = medicines.getProducterId();
            Integer conversion = medicines.getConversion();
            String unit = medicines.getUnit();
            InventoryLog inventoryLog = new InventoryLog(id,purchaseId,medicinesId, purchaseNumber, tradePrice,
                    prescriptionPrice,tradeTotalAmount,inventoryTotalAmount,batchNumber,medicinesName,medicinesType,
                    prescriptionType, producterId,conversion,unit,providerId,new Date(),userName);
            inventoryLogMapper.insert(inventoryLog);
        }
        return R.ok();
    }

    @Override
    public R auditPass(String purchaseId) {
        //更改采购单的状态为3，表示审核通过
        Purchase purchase = purchaseMapper.selectById(purchaseId);
        if (purchase != null) {
            purchase.setStatus(getStatus("审核通过"));
            purchaseMapper.updateById(purchase);
            return R.ok();
        }
        return R.error("采购单不存在");
    }
    @Override
    public R auditNoPass(String purchaseId, String reason)  {
        //更改采购单的状态为3，表示审核通过
        Purchase purchase = purchaseMapper.selectById(purchaseId);
        if (purchase != null) {
            purchase.setStatus(getStatus("审核失败"));
            purchase.setAuditMsg(reason);
            purchaseMapper.updateById(purchase);
            return R.ok();
        }
        return R.error("采购单不存在");
    }

    @Override
    public R<List<PurchaseItem>> getPurchaseItemById(String purchaseId) {
        IPage<PurchaseItem> page =new Page<>(1,5);
        QueryWrapper<PurchaseItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("purchase_id",purchaseId);
        IPage<PurchaseItem> purchaseIPage = purchaseItemMapper.selectPage(page, queryWrapper);
        System.out.println("++++++++++++++++");
        System.out.println(purchaseIPage.getRecords());
        return R.ok(purchaseIPage.getRecords());
    }

    @Override
    public R<String> generatePurchaseId() {
        //雪花算法生成采购单id，hutools工具包
        Snowflake snowflake = IdUtil.getSnowflake();
        String id = ""+snowflake.nextId();
        if (id != null) {
            System.out.println("++++++++++++");
            System.out.println("生成的采购单id为："+id);
            return R.ok(id);
        }
        return R.error("生成采购单id失败");
    }
    /*

        public R addPurchase(Map<String,Object> purchaseItems) {
            // 将list中的数据转成json字符串
            String jsonObject= JSON.toJSONString(purchaseItems);
            //将json转成需要的对象
            PurcheseObj purcheseObj = JSONObject.parseObject(jsonObject, PurcheseObj.class);
            System.out.println(purcheseObj);
            System.out.println("purchaseItems:"+purchaseItems.toString());
            PurchaseDto purchaseDto = purcheseObj.getPurchaseDto();
            System.out.println("purchaseDto:"+purchaseDto.toString());
            PurchaseItemDtos purchaseItemDtos = purcheseObj.getPurchaseItemDtos();
            System.out.println("purchaseItemDtos:"+purchaseItemDtos.toString());
            List<PurchaseItemDto> purchaseItemDtos1 = purchaseItemDtos.getPurchaseItemDtos();
            if (purchaseDto != null&&purchaseItemDtos1 != null) {
                String purchaseId = purchaseDto.getPurchaseId();
                Purchase purchase = purchaseMapper.selectById(purchaseId);
                if (purchase != null) {
                    purchase.setStatus("1");
                    purchase.setCreateBy( WebUtil.getUsername());
                    purchase.setProviderId(purchaseDto.getProviderId());
                    purchase.setPurchaseTradeTotalAmount( purchaseDto.getPurchaseTradeTotalAmount());
                    purchaseMapper.insert(purchase);
                    for (PurchaseItemDto purchaseItemDto : purchaseItemDtos1) {
                        PurchaseItem purchaseItem = new PurchaseItem();
                        BeanUtils.copyProperties(purchaseItemDto,purchaseItem);
                        System.out.println(purchaseItem);
                        purchaseItem.setPurchaseId(purchaseDto.getPurchaseId());
                        //雪花算法生成采购单id，hutools工具包
                        Snowflake snowflake = IdUtil.getSnowflake();
                        String id = "CF"+snowflake.nextId();
                        if (id != null) {
                            System.out.println("++++++++++++生成的采购单id为："+id);
                            purchaseItem.setItemId(id);
                        }
                        else {return R.error("生成采购单id失败");}
                        purchaseItemMapper.insert(purchaseItem);
                    }
                    return R.ok();
                }
            }
            return R.error("数据错误");
        }

    */
//暂存
    @Override
    public R erpAddPurchase(List<PurchaseItem> purchaseItems) {
        Snowflake snowflake = IdUtil.getSnowflake();
        String purchaseId = purchaseItems.get(0).getPurchaseId();
        Purchase purchase = purchaseMapper.selectById(purchaseId);
        if (purchase == null) {
            purchase = new Purchase();
            purchase.setPurchaseId(purchaseId);
            purchase.setStatus(getStatus("未提交"));
            purchaseMapper.insert(purchase);
        }
        else {purchase.setStatus(getStatus("未提交"));}
        purchaseItemMapper.delete(new QueryWrapper<PurchaseItem>().eq("purchase_id",purchaseId));
        for (PurchaseItem purchaseItem : purchaseItems) {
            String id = "" + snowflake.nextId();
            if (purchaseItem.getItemId() == null) {
                purchaseItem.setItemId(id);
            }
            System.out.println("purchaseItemid+++++++++"+purchaseItem.getPurchaseId());
            purchaseItemMapper.insert(purchaseItem);
            //purchaseItemMapper.update(purchaseItem,new QueryWrapper<PurchaseItem>().eq("item_id",id));
        }
        return R.ok();
    }
    //添加审核
    @Override
    public R addPurchaseToAudit(List<PurchaseItem> purchaseItems) {
        System.out.println("purchaseItems+++++++++++++"+purchaseItems.toString());
        Snowflake snowflake = IdUtil.getSnowflake();
        String purchaseId = purchaseItems.get(0).getPurchaseId();
        System.out.println("purchaseId+++++++++++++"+purchaseId);
        Purchase purchase = new Purchase();
        purchase.setPurchaseId(""+purchaseId);
        purchase.setStatus(getStatus("待审核"));
        boolean flag = purchaseMapper.exists(new QueryWrapper<Purchase>().eq("purchase_id", purchaseId));
        if (flag) {
            purchaseMapper.update(purchase, new QueryWrapper<Purchase>().eq("purchase_id", purchaseId));
        } else {
            purchaseMapper.insert(purchase);
        }
        for (PurchaseItem purchaseItem : purchaseItems) {
            String id = "" + snowflake.nextId();
            if (purchaseItem.getItemId() == null) {
                purchaseItem.setItemId(id);
                System.out.println("itemid+++++++++++" +purchaseItem.getItemId());
            }
            purchaseItemMapper.insert(purchaseItem);
            System.out.println("purchaseItem)+++++++++++++"+ purchaseItem.toString());
        }
        return R.ok();
    }
    //修改purcahse,加字段
    public  R updateByPurchaseId(PurchaseDto purchaseDto){
        BigDecimal purchaseTradeTotalAmount = purchaseDto.getPurchaseTradeTotalAmount();
        String providerId = purchaseDto.getProviderId();
        String purchaseId = purchaseDto.getPurchaseId();
        try {
            //等待500ms
            Thread.sleep(500);
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("改字段purchaseId+++++++++++++"+purchaseId+"purchaseTradeTotalAmount++++++++++++"+purchaseTradeTotalAmount+"providerId++++++++++++"+providerId);
        boolean flag = purchaseMapper.exists(new QueryWrapper<Purchase>().eq("purchase_id", purchaseId));
        Purchase purchase = new Purchase();
        System.out.println("是否存在+++++++++++++++++++++++++++++++++++++++++++++++++"+flag);
        purchase.setPurchaseTradeTotalAmount(purchaseTradeTotalAmount);
        purchase.setProviderId(providerId);
        purchase.setStatus(getStatus("待审核"));
        String username = WebUtil.getUsername();
   User data = userFeign.getByPhone(username).getData();
        String userName = data.getUserName();
     purchase.setCreateBy(username);
        purchase.setCreateTime(new Date());
     purchase.setApplyUserId(data.getUserId());
        purchase.setApplyUserName(username);
        purchase.setPurchaseId(purchaseId);
        System.out.println("改字段purchase+++++++++++++"+purchase.toString());

//        if (flag){
           purchaseMapper.updateById(purchase);
//        }
//        else {
//            purchaseMapper.insert(purchase);
//        }
        return R.ok();
    }

    @Override
    public R updateStatusByPurchaseId(PurchaseDto purchaseDto) {
        BigDecimal purchaseTradeTotalAmount = purchaseDto.getPurchaseTradeTotalAmount();
        String providerId = purchaseDto.getProviderId();
        String purchaseId = purchaseDto.getPurchaseId();
        System.out.println("改字段purchaseId+++++++++++++"+purchaseId+"purchaseTradeTotalAmount++++++++++++"+purchaseTradeTotalAmount+"providerId++++++++++++"+providerId);
        boolean flag = purchaseMapper.exists(new QueryWrapper<Purchase>().eq("purchase_id", purchaseId));
        Purchase purchase = new Purchase();
        System.out.println("是否存在+++++++++++++++++++++++++++++++++++++++++++++++++"+flag);
        purchase.setPurchaseTradeTotalAmount(purchaseTradeTotalAmount);
        purchase.setProviderId(providerId);
        purchase.setStatus(getStatus("未提交"));
        String username = WebUtil.getUsername();
 User data = userFeign.getByPhone(username).getData();
String userName = data.getUserName();
        purchase.setCreateBy(username);
        purchase.setCreateTime(new Date());
 purchase.setApplyUserId(data.getUserId());
        purchase.setApplyUserName(username);
        purchase.setPurchaseId(purchaseId);
        System.out.println("改字段purchase+++++++++++++"+purchase.toString());
//        if (flag){
            purchaseMapper.updateById(purchase);
//        }
//        else {
//            purchaseMapper.insert(purchase);
//        }
        return R.ok();
    }

    @Override
    public R<Map<String, Object>> queryPurchaseAndItemByPurchaseId2(String purchaseId) {
        QueryWrapper<PurchaseItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("purchase_id",purchaseId);
        List<PurchaseItem> purchaseItems = purchaseItemMapper.selectList(queryWrapper);

        Purchase purchase = purchaseMapper.selectById(purchaseId);

        Map<String, Object> map = new HashMap<>();
        map.put("purchase",purchase);
        map.put("purchaseItems",purchaseItems);
        return R.ok(map);
    }

    @Override
    public R<List<PurchaseItem>> queryPurchaseAndItemByPurchaseId(String purchaseId) {
        QueryWrapper<PurchaseItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("purchase_id",purchaseId);
        List<PurchaseItem> purchaseItems = purchaseItemMapper.selectList(queryWrapper);
        if (purchaseItems.size() > 0) {
            return R.ok(purchaseItems);
        }
        return R.error("数据错误");
    }
}



